import 'dart:io';

import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_static/shelf_static.dart';
import 'package:path/path.dart' as p;
import 'package:shelf/shelf_io.dart' as io;

import 'package:starkylin_file_shared/src/utils/general.dart';

void Function(Null arg)? serverFileFunc;

class IsolateArg {
  int? port;
}

final corsHeader = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': '*',
  'Access-Control-Allow-Methods': '*',
  'Access-Control-Allow-Credentials': 'true',
};
var fileRouter = Router();

class ServerUtil {
  static Future<String> serveFile(String path, int port) async {
    String filePath = path.replaceAll('\\', '/');
    filePath = filePath.replaceAll(RegExp('^[A-Z]:'), '');
    filePath = filePath.replaceAll(RegExp('^/'), '');
    // 部署文件
    String url = p.toUri(filePath).toString();
    var handler = createFileHandler(path, url: url);
    fileRouter.get('/$url', handler);
    log("servePath: http://localhost:$port/$url");

    await io.serve(
      fileRouter.call,
      'localhost',
      port,
      shared: true,
    );

    return "/$url";
  }
}
